package cn.ai.shoes.core.handler;

import cn.ai.shoes.core.service.UserService;
import cn.ai.shoes.core.utils.AuthenticationUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    // 修改为构造器注入
    private final UserService userService;

    /**
     * 登录成功后执行的方法
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String json = AuthenticationUtils.response(userDetails, userService, AuthenticationUtils.PASSWORD_LOGIN_PROCESSOR);
        // 设置响应头
        response.setContentType("application/json;charset=utf-8");
        // 设置响应体
        response.getWriter().print(json);
    }

}
